package com.boe.config.interceptor.controller;

import com.boe.common.annotation.OpenAction;
import com.boe.config.service.LoginUserService;
import com.boe.config.spring.HttpContext;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;


@Component
@RequiredArgsConstructor
public class DefaultMvcInterceptor implements HandlerInterceptor {

    @NotNull
    LoginUserService loginUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (response.getStatus() >= 400 && response.getStatus() <= 600) {
            return true;
        }

        if (handler instanceof HandlerMethod == false) {
            return true;
        }

        var url = request.getRequestURI();
        if (url.startsWith("/open/") ||
                url.startsWith("/open-")
        ) {
            return true;
        }


        var beanType = ((HandlerMethod) handler).getBeanType();
        var annotations = beanType.getAnnotations();
        if (Arrays.stream(annotations).anyMatch(it -> it instanceof OpenAction)) {
            return true;
        }


        //通过 token 获取用户信息
        var token = request.getHeader("token");
        var loginUser = loginUserService.getLoginUserInfo(token);

        if (loginUser == null) {
            response.setStatus(401);
            return false;
        }

        HttpContext.setLoginUser(loginUser);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
